package Str;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * @auther wangchenghao
 * @date 2021/6/14
 **/
public class test8 {
    public static String countAndSay(int n) {
        if (n==1){
            return "1";
        }
        return read(countAndSay(n-1));
    }

    public static String read(String n){
        int length=n.length();
        ArrayList<String> classy = new ArrayList<>();
        char[] chars = n.toCharArray();
        int hang=0;
        int i=0;
        int j=0;
        while (i < chars.length) {
            char index=chars[i];
            String s=String.valueOf(chars[i]);
            for (j = i+1; j <chars.length ; j++) {

                if (index==chars[j]){
                    s+=String.valueOf(chars[j]);
                }else {

                    break;
                }
            }
            i=j;
            classy.add(s);
        }
        String result="";
        Iterator<String> iterator = classy.iterator();
        //iterator.hasNext()如果存在元素的话返回true
        while(iterator.hasNext()) {
            //iterator.next()返回迭代的下一个元素
            String s=iterator.next();
            System.out.println("String.valueOf(s.length()) = " + String.valueOf(s.length()));
            System.out.println("s.indexOf(0) = " + s.substring(0,1));
            result+=String.valueOf(s.length())+""+s.substring(0,1);
        }
        return result;
    }
    public static String countAndSay2(int n) {
        if (n==1){
            return "1";
        }
        StringBuffer stringBuffer=new StringBuffer("1");
        while (--n>0){
            StringBuffer s2=new StringBuffer();
            int index=1;
            int i=0;
            for ( i = 0; i <stringBuffer.length()-1; i++) {
                if (stringBuffer.charAt(i)==stringBuffer.charAt(i+1)){
                    index++;
                }else {
                    s2.append(index).append(stringBuffer.charAt(i));
                }
            }
            s2.append(index).append(stringBuffer.charAt(i));
            stringBuffer=s2;
        }
        return stringBuffer.toString();

    }
    public static void main(String[] args) {
        System.out.println("countAndSay2(4) = " + countAndSay2(4));
    }
}
